using System.Reflection;
using BuildingBlocks.Abstractions.Permissions;
using Microsoft.AspNetCore.Mvc;

namespace Identity.HttpAPI.Permission;

public class PermissionScannerProvider : IPermissionProvider
{
    private readonly Assembly _assembly;

    public PermissionScannerProvider(Assembly assembly)
    {
        _assembly = assembly;
    }

    public IEnumerable<PermissionDefinition> GetPermissions()
    {
        return _assembly.GetTypes()
            .Where(t => typeof(ControllerBase).IsAssignableFrom(t))
            .SelectMany(t => t.GetMethods())
            .SelectMany(m => m.GetCustomAttributes<PermissionAttribute>())
            .Select(attr => new PermissionDefinition(attr.ResourceId, attr.Description));
    }
}
